package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.entity.YddUserData;
import com.itheima.ydd.service.IYddArticleService;
import com.itheima.ydd.service.IYddCateService;
import com.itheima.ydd.service.IYddUserDataService;
import com.itheima.ydd.service.IYddUserService;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IYddUserService yddUserService;
    @Autowired
    private IYddUserDataService yddUserDataService;
    @Autowired
    private IYddArticleService yddArticleService;
    @Autowired
    private IYddCateService yddCateService;

    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public ResultData getUserInfo(HttpServletRequest request) {
        Map<String, Object> data = new HashMap<>();
        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId=" + userId);

        YddUser user = yddUserService.getById(userId);
        user.setPassword("");
        data.put("userInfo", user);

        //获取用户发布的文章数
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getUserId, userId);
        int articleNum = yddArticleService.count(lqw);
        data.put("articleNum", articleNum);

        //获取用户收藏的文章数
        LambdaQueryWrapper<YddUserData> yddUserDataLqw = new LambdaQueryWrapper<>();
        yddUserDataLqw.eq(YddUserData::getUserId, userId);
        yddUserDataLqw.eq(YddUserData::getType, 1);
        int collectNum = yddUserDataService.count(yddUserDataLqw);
        data.put("collectNum", collectNum);

        //获取用户点赞的文章数
        LambdaQueryWrapper<YddUserData> yddUserDataLqw2 = new LambdaQueryWrapper<>();
        yddUserDataLqw2.eq(YddUserData::getUserId, userId);
        yddUserDataLqw2.eq(YddUserData::getType, 2);
        int zanNum = yddUserDataService.count(yddUserDataLqw2);
        data.put("zanNum", zanNum);

        return ResultData.ok("", data);
    }

    /**
     * 获取收藏和点赞文章列表
     *
     * @param page
     * @param limit
     * @param type
     * @param request
     * @return
     */
    @GetMapping("/userDataList")
    public ResultData getUserDataList(Long page, Long limit, Long type, HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        Page<YddUserData> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<YddUserData> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddUserData::getUserId, userId);
        lqw.eq(YddUserData::getType, type);
        lqw.orderByDesc(YddUserData::getId);
        yddUserDataService.page(pageInfo, lqw);
        List<YddUserData> yddUserDataList = pageInfo.getRecords();
        System.out.println("yddUserDataList=" + yddUserDataList);

        List<YddArticle> articles = new ArrayList<>();

        for (YddUserData yddUserData : yddUserDataList) {
            Integer articleId = yddUserData.getArticleId();
            YddArticle article = yddArticleService.getById(articleId);
            if (article != null) {
                articles.add(article);
            }
        }

        List<YddArticleDto> dataList = articles.stream().map(item -> {
            YddArticleDto yddArticleDto = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDto);

            LambdaQueryWrapper<YddCate> yddCateLqw = new LambdaQueryWrapper<>();
            yddCateLqw.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = yddCateService.getOne(yddCateLqw);
            yddArticleDto.setCatename(yddCate.getCatename());
            return yddArticleDto;
        }).collect(Collectors.toList());

        Map<String, Object> data = new HashMap<>();
        Map<String, Object> list = new HashMap<>();
        list.put("data", dataList);
        list.put("count", pageInfo.getTotal());
        list.put("totalPages", pageInfo.getPages());
        list.put("currentPage", pageInfo.getCurrent());
        list.put("pageSize", pageInfo.getSize());
        data.put("list", list);

        return ResultData.ok("", data);
    }
   /* *//**
     * 点赞/取消点赞和收藏/取消收藏
     * @param type
     * @param action
     * @param articleId
     * @return
     */
    @GetMapping("/userDataHandle")
    private ResultData userDataHandle(Long type,String action,@RequestParam("article_id") Long articleId,HttpServletRequest request){
        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        //add表示点赞或收藏，del表示取消点赞或取消收藏
        if (StringUtils.isNotEmpty(action) && "del".equals(action)){
            LambdaQueryWrapper<YddUserData> lqw=new LambdaQueryWrapper<>();
            lqw.eq(StringUtils.isNotEmpty(String.valueOf(articleId)),YddUserData::getArticleId,articleId);
            lqw.eq(StringUtils.isNotEmpty(String.valueOf(type)),YddUserData::getType,type);
            lqw.eq(YddUserData::getUserId,userId);
            yddUserDataService.remove(lqw);
            return ResultData.ok("","");
        }else if (StringUtils.isNotEmpty(action) && "add".equals(action)){
            YddUserData userData=new YddUserData();
            userData.setArticleId(Math.toIntExact(articleId));
            userData.setUserId(userId);
            userData.setType(Math.toIntExact(type));
            yddUserDataService.save(userData);
            return ResultData.ok("","");
        }
        return ResultData.error("无法操作!!!");
    }

    /**
     * 修改个人资料
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddUser yddUser) {
        if (StringUtils.isNotEmpty(yddUser.getPassword())) {
            String password = DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes());
            yddUser.setPassword(password);
        } else {
            YddUser user = yddUserService.getById(yddUser.getId());
            yddUser.setPassword(user.getPassword());
        }
        yddUserService.updateById(yddUser);
        return ResultData.ok("修改成功", "");
    }

    /**
     * 获取我的文章
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/myArticle")
    public ResultData getMyArticle(Long page, Long limit, HttpServletRequest request) {
        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        Page<YddArticle> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getUserId, userId);
        lqw.orderByDesc(YddArticle::getCreateDate);
        yddArticleService.page(pageInfo, lqw);

        return ResultData.ok("", PageResult.init(pageInfo.getTotal(), page, limit, pageInfo.getRecords()));
    }

    /**
     * 发布文章
     *
     * @return
     */
    @PostMapping("/addArticle")
    public ResultData addArticle(@RequestBody YddArticle yddArticle, HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        yddArticle.setCreateDate(System.currentTimeMillis());
        yddArticle.setUpdateDate(System.currentTimeMillis());
        yddArticle.setUserId(userId);

        yddArticleService.save(yddArticle);
        return ResultData.ok("发布成功", "");
    }

    /**
     * 修改文章
     *
     * @return
     */
    @PostMapping("/editArticle")
    public ResultData editArticle(@RequestBody YddArticle yddArticle, HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        yddArticle.setUpdateDate(System.currentTimeMillis());
        yddArticle.setUserId(userId);
        yddArticleService.updateById(yddArticle);
        return ResultData.ok("修改成功", "");
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @GetMapping("/delArticle")
    public ResultData deleteArticle(Long id) {
        yddArticleService.removeById(id);
        LambdaQueryWrapper<YddUserData> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddUserData::getArticleId, id);
        yddUserDataService.remove(lqw);
        return ResultData.ok("删除成功", "");
    }
}
